"use client";

import ClientLoading from "@/components/ClientLoading";
import { Form, Input } from "@/components/Form";
import Tab from "@/components/Tab";
import { POST, PUT } from "@/utils/fetch";
import { useRouter } from "next/navigation";
import React, { useState } from "react";

const emptyNode: SubmeNode = {
  type: "vmess",
  host: "",
  name: "",
  port: 443,
  password: "",
  path: "/",
};

const nodeTypes: SubmeNodeType[] = ["vmess", "trojan"];
const tabNodeTypes: { value: string; label: string }[] = nodeTypes.map((t) => ({
  value: t.toString(),
  label: t.toString(),
}));

export default function NodeInputUI({
  data = { ...emptyNode },
}: {
  data?: SubmeNode;
}) {
  const [node, setNode] = useState(data);
  const [isLoading, setLoading] = useState(false);
  const router = useRouter();

  const changeValue =
    (key: string) => (e: React.ChangeEvent<HTMLInputElement>) => {
      const v = e.target.value.trim();
      if (key === "port") {
        const port = parseInt(v, 10) || 443;
        setNode({ ...node, port });
        return;
      }
      setNode({ ...node, [key]: v });
    };

  const submitHandler = async () => {
    setLoading(true);
    try {
      const resp: JsonResp<any> = node.id
        ? await PUT("/node", { ...node })
        : await POST("/node", { ...node });
      if (resp.code !== 0) {
        throw new Error(resp.msg);
      }
      router.push(`/node?msg=操作成功&_r=${Math.random()}`);
    } catch (e) {
      alert((e as Error).message);
      console.log(e);
    } finally {
      setLoading(false);
    }
  };
  return (
    <>
      {/* <div>{JSON.stringify(node)}</div> */}
      {isLoading && <ClientLoading />}
      <Form onSubmit={submitHandler}>
        <Tab
          items={tabNodeTypes}
          value={node.type.toString()}
          onChange={(v) => setNode({ ...node, type: v as SubmeNodeType })}
        />
        <Input
          label="名称"
          value={node.name}
          onChange={changeValue("name")}
          required
        />
        <Input
          label="主机"
          value={node.host}
          onChange={changeValue("host")}
          required
        />
        <Input
          label="端口"
          value={node.port}
          onChange={changeValue("port")}
          type="number"
          required
        />
        <Input
          label={node.type === "vmess" ? "UUID" : "密码"}
          value={node.password}
          onChange={changeValue("password")}
          required
        />
        <Input
          label="路径"
          value={node.path}
          onChange={changeValue("path")}
          required
        />
      </Form>
    </>
  );
}
